package cn.wjdiankong.levideo;

import java.io.File;
import java.util.List;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.ss.android.common.applog.GlobalContext;
import com.ss.android.common.applog.UserInfo;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.EScenarioType;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import cn.wjdiankong.hookpms.ServiceManagerWraper;
import cn.wjdiankong.levideo.database.LocalStorage;
import cn.wjdiankong.levideo.douyin.utils.DouyinUtils;
import cn.wjdiankong.levideo.hotsoon.utils.HotsoonUtils;
import cn.wjdiankong.levideo.kuaishou.utils.KuaishouUtils;
import cn.wjdiankong.levideo.miaopai.utils.MiaopaiUtils;
import cn.wjdiankong.levideo.utils.FileUtils;
import cn.wjdiankong.levideo.utils.Logger;
import cn.wjdiankong.levideo.utils.Utils;
import net.youmi.android.AdManager;

public class MainApplication extends Application{
	
	@Override
	public void onCreate() {
		super.onCreate();
		//为了解决抖音的签名校验问题
		//ServiceManagerWraper.hookPMS(this.getApplicationContext());
		//抖音的全局Context设置
		GlobalContext.setContext(getApplicationContext());
		LocalStorage.getInstance().setContext(getApplicationContext());
		//加载so文件
		try{
			System.loadLibrary("userinfo");//抖音&火山
			System.loadLibrary("core");//快手
			System.loadLibrary("te");//秒拍
		}catch(Exception e){
			Logger.log("load so err:"+Log.getStackTraceString(e));
		}
		//抖音初始化操作
		UserInfo.setAppId(2);
		UserInfo.initUser("a3668f0afac72ca3f6c1697d29e0e1bb1fef4ab0285319b95ac39fa42c38d05f");
		//删除临时文件
		FileUtils.clearFile(getApplicationContext());
		//初始化四家短视频app的版本信息
		initAppVersion();
		
		//初始化位置信息
		//initLocationInfo();
		
		CrashHandler handler = CrashHandler.getInstance();  
		handler.init(getApplicationContext());
		Thread.setDefaultUncaughtExceptionHandler(handler); 
		
		initImageLoader(this);
		
		MobclickAgent.setDebugMode(false);
        // SDK在统计Fragment时，需要关闭Activity自带的页面统计，
        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。
        MobclickAgent.openActivityDurationTrack(false);
        MobclickAgent.setScenarioType(getApplicationContext(), EScenarioType.E_UM_NORMAL);
        
        //初始化SDK
		AdManager.getInstance(GlobalContext.getContext()).init("a572560546902bb9", "17356114735c7424", true);
		
	}
	
	private void initImageLoader(Context context) {
		ImageLoaderConfiguration config = new ImageLoaderConfiguration   
		          .Builder(context)   
		          .threadPoolSize(5)//线程池内加载的数量   
		          .threadPriority(Thread.NORM_PRIORITY -2) 
		          .denyCacheImageMultipleSizesInMemory()
		          .memoryCacheSize(10 * 1024 * 1024)
		          .discCacheSize(50 * 1024 * 1024)
		          .discCacheFileNameGenerator(new Md5FileNameGenerator())//将保存的时候的URI名称用MD5 加密   
		          .tasksProcessingOrder(QueueProcessingType.LIFO)   
		          .discCacheFileCount(500)//缓存的文件数量  
		          .discCache(new UnlimitedDiscCache(new File(FileUtils.getCacheImgPath(getApplicationContext()))))//自定义缓存路径   
		          .defaultDisplayImageOptions(DisplayImageOptions.createSimple())   
		          .build();//开始构建  
		ImageLoader.getInstance().init(config); 
	}
	
	private void initAppVersion(){
		try{
			List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);
			for(int i=0;i<packages.size();i++) { 
				PackageInfo packageInfo = packages.get(i);
				if(DouyinUtils.PKGNAME.equals(packageInfo.packageName)){
					DouyinUtils.appVersionCode = packageInfo.versionCode+"";
					DouyinUtils.appVersionName = packageInfo.versionName;
				}else if(HotsoonUtils.PKGNAME.equals(packageInfo.packageName)){
					HotsoonUtils.appVersionCode = packageInfo.versionCode+"";
					HotsoonUtils.appVersionName = packageInfo.versionName;
				}else if(MiaopaiUtils.PKGNAME.equals(packageInfo.packageName)){
					MiaopaiUtils.appVersionCode = packageInfo.versionCode+"";
					MiaopaiUtils.appVersionName = packageInfo.versionName;
				}else if(KuaishouUtils.PKGNAME.equals(packageInfo.packageName)){
					KuaishouUtils.appVersionCode = packageInfo.versionCode+"";
					KuaishouUtils.appVersionName = packageInfo.versionName;
				}
			}
		}catch(Exception e){
			Logger.log("init app version err:"+Log.getStackTraceString(e));
		}
	}
	
	public void initLocationInfo(){
		String locationProvider = null;
		try{
			//获取地理位置管理器  
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
	        //获取所有可用的位置提供器  
	        List<String> providers = locationManager.getProviders(true);  
	        if(providers.contains(LocationManager.GPS_PROVIDER)){  
	            //如果是GPS  
	            locationProvider = LocationManager.GPS_PROVIDER;  
	        }else if(providers.contains(LocationManager.NETWORK_PROVIDER)){  
	            //如果是Network  
	            locationProvider = LocationManager.NETWORK_PROVIDER;  
	        }else{
	        	return;
	        }
	        //获取Location  
	        Location location = locationManager.getLastKnownLocation(locationProvider);  
	        if(location!=null){  
	            //不为空,显示地理位置经纬度  
	        	Utils.lnglat[0] = location.getLongitude();
	            Utils.lnglat[1] = location.getLatitude(); 
	        }  
	        //监视地理位置变化  
	        locationManager.requestLocationUpdates(locationProvider, 3000, 1, new LocationListener() {  
	            @Override  
	            public void onStatusChanged(String provider, int status, Bundle bundle) {  
	            }  
	            @Override  
	            public void onProviderEnabled(String provider) {  
	                  
	            }  
	            @Override  
	            public void onProviderDisabled(String provider) {  
	                  
	            }  
	            @Override  
	            public void onLocationChanged(Location location) {  
	                //如果位置发生变化,重新显示  
		            Utils.lnglat[0] = location.getLongitude();
		            Utils.lnglat[1] = location.getLatitude(); 
	                  
	            }  
	        });  
		}catch(Exception e){
		}
	}

}
